<template>
  <div>
    <el-upload
      :action="UPLOAD_URL"
      :file-list="values"
      :multiple="true"
      :on-success="onXdUploadSuccess"
      :on-preview="handlePictureCardPreview"
      :on-remove="handleRemove"
      accept="image/*"
      list-type="picture-card"
    >
      <i class="el-icon-plus"/>
    </el-upload>
    <el-dialog :visible.sync="dialogVisible" :append-to-body="true">
      <div class="text-center">
        <img :src="dialogImageUrl" alt style="max-width:100%;">
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'XdUpload',

  model: {
    prop: 'imgSrcs',
    event: 'change'
  },
  props: {
    imgSrcs: {
      type: String,
      default: ''
    }
  },
  data () {
    return {
      values: [],
      dialogImageUrl: '',
      dialogVisible: false
    }
  },
  watch: {
    imgSrcs () {
      if (!this.hasChanged) {
        if (this.imgSrcs) {
          const data = this.imgSrcs.split(',').map(el => {
            return {
              name: '',
              url: this.imgUrl(el)
            }
          })
          this.values = data
        } else {
          this.values = []
        }
      } else {
        this.hasChanged = false
      }
    }
  },
  // computed: {
  //   values () {
  //     if (this.imgSrcs) {
  //       const data = this.imgSrcs.split(',').map(el => {
  //         return {
  //           name: '',
  //           url: this.imgUrl(el)
  //         }
  //       })
  //       return data
  //     } else {
  //       return []
  //     }
  //   }
  // },
  methods: {
    onXdUploadSuccess (e, file, fileList) {
      console.log('onXdUploadSuccess')
      // if (fileList.some(el => el.percentage !== 100)) {
      //   return
      // }
      console.log(fileList.map(el => el.response.info).join(','))
      this.hasChanged = true
      this.$emit('change', fileList.map(el => el.response.info).join(','))
    },
    handleRemove (file, fileList) {
      this.$emit('change', fileList.map(el => el.response.info).join(','))
    },
    handlePictureCardPreview (file) {
      this.dialogImageUrl = file.url
      this.dialogVisible = true
    }
  }
}
</script>
